package org.bot.plugin.data.event;

import com.alibaba.fastjson.JSONObject;
import org.bot.api.event.DataStorage;
import org.bot.api.event.EventName;
import org.bot.api.event.Events;
import org.bot.api.flow.FlowNode;
import org.bot.api.util.StringUtil;
import org.springframework.stereotype.Component;

/**
 * @author 沧月
 * @create 0028 2023/9/28 17:22
 * @description <设置节点输出值>
 */
@Component
@EventName("设置节点值")
public class DataSetNodeValue implements Events {

    @Override
    public Object exec(FlowNode node, DataStorage data) {
        JSONObject object = JSONObject.parseObject(node.getArg());
        String nodeId = object.getString("nodeId");

        Object value = null;
        if (StringUtil.isNotNull(node.getDataIndex())) {
            value = data.get(node.getDataIndex());
        } else {
            switch (object.getString("type")) {
                case "bool":
                    value = object.getBoolean("value");
                    break;
                case "int":
                    value = object.getInteger("value");
                    break;
                case "string":
                    value = object.getString("value");
                    break;
                case "float":
                    value = object.getFloat("value");
                    break;
                case "json_array":
                    value = object.getJSONArray("value");
                    break;
                case "json_object":
                    value = object.getJSONObject("value");
                    break;
            }
        }
        if (StringUtil.isNotNull(nodeId)) {
            data.put(nodeId, value);
            return null;
        } else {
            return value;
        }
    }
}
